import { createSlice } from '@reduxjs/toolkit'

export const counterSlice = createSlice({
    // 命名空间，在调用action的时候会默认的设置为action的前缀,保证唯一.不重名
    name: 'counter',
    initialState: {
        value: 0,
    },
    reducers: {
         // 定义的action-赋值的方式进行数据的改变
        increment: (state) => {
            state.value += 1
        },
        decrement: (state) => {
            state.value -= 1
        },
        incrementByAmount: (state, action) => {
            state.value += action.payload
        },
    },
})

// 导出action
export const { increment, decrement, incrementByAmount } = counterSlice.actions

// 异步数据处理
export const incrementAsync = (amount) => (dispatch) => {
    setTimeout(() => {
        dispatch(incrementByAmount(amount))
    }, 1000)
}

export const selectCount = (state) => state.counter.value

// 导出reducer
export default counterSlice.reducer